package com.example.raspberrypicar

import android.os.Bundle
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import android.view.View

class MainActivity : AppCompatActivity(), JoystickView.JoystickListener {

    // 状态显示组件
    private lateinit var batteryStatus: TextView
    private lateinit var signalStatus: TextView
    private lateinit var speedStatus: TextView
    private lateinit var temperatureStatus: TextView
    private lateinit var connectionStatus: TextView
    private lateinit var gpsStatus: TextView
    private lateinit var videoStatus: TextView

    // 操纵杆
    private lateinit var joystickView: JoystickView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // 初始化组件
        initViews()

        // 设置操纵杆监听器
        joystickView.setJoystickListener(this)

        // 设置机器人区域点击事件
        setupRobotButtons()

        // 开始状态更新
        startStatusUpdates()
    }

    /**
     * 初始化视图组件
     */
    private fun initViews() {
        batteryStatus = findViewById(R.id.battery_status)
        signalStatus = findViewById(R.id.signal_status)
        speedStatus = findViewById(R.id.speed_status)
        temperatureStatus = findViewById(R.id.temperature_status)
        connectionStatus = findViewById(R.id.connection_status)
        gpsStatus = findViewById(R.id.gps_status)
        videoStatus = findViewById(R.id.video_status)
        joystickView = findViewById(R.id.joystick_view)
    }

    /**
     * 设置机器人区域点击事件
     */
    private fun setupRobotButtons() {
        val robot1 = findViewById<android.widget.LinearLayout>(R.id.robot_1)
        val robot2 = findViewById<android.widget.LinearLayout>(R.id.robot_2)
        val robot3 = findViewById<android.widget.LinearLayout>(R.id.robot_3)

        robot1.setOnClickListener {
            showMessage("机器人1 - 功能待开发")
        }

        robot2.setOnClickListener {
            showMessage("机器人2 - 功能待开发")
        }

        robot3.setOnClickListener {
            showMessage("机器人3 - 功能待开发")
        }
    }

    /**
     * 开始状态更新
     */
    private fun startStatusUpdates() {
        val handler = android.os.Handler()
        val updateRunnable = object : Runnable {
            override fun run() {
                updateAllStatus()
                handler.postDelayed(this, 1000)
            }
        }
        handler.post(updateRunnable)
    }

    /**
     * 更新所有状态信息
     */
    private fun updateAllStatus() {
        // 模拟数据更新
        val batteryLevel = (10..100).random()
        batteryStatus.text = "🔋 电量: $batteryLevel%"

        if (batteryLevel < 20) {
            batteryStatus.setTextColor(getColor(android.R.color.holo_red_dark))
        } else {
            batteryStatus.setTextColor(getColor(android.R.color.black))
        }

        val signals = arrayOf("弱", "中", "强")
        val signal = signals.random()
        signalStatus.text = "📶 信号: $signal"

        val temperature = (20..35).random()
        temperatureStatus.text = "🌡️ 温度: ${temperature}°C"

        connectionStatus.text = "🔗 连接: 已连接"
        gpsStatus.text = "📍 GPS: 已定位"

        // 更新视频状态
        videoStatus.text = "实时视频流 - ${(0..100).random()}%"
    }

    /**
     * 操纵杆移动回调
     */
    override fun onJoystickMoved(xPercent: Float, yPercent: Float, source: JoystickView) {
        // 更新速度显示（基于操纵杆移动距离）
        val distance = Math.sqrt((xPercent * xPercent + yPercent * yPercent).toDouble()).toFloat()
        val speed = distance * 5f // 最大速度5m/s
        speedStatus.text = "⚡ 速度: ${"%.1f".format(speed)} m/s"

        // 发送控制指令
        sendControlCommand(xPercent, -yPercent) // 反转Y轴，使向上推为前进
    }

    /**
     * 操纵杆释放回调
     */
    override fun onJoystickReleased(source: JoystickView) {
        speedStatus.text = "⚡ 速度: 0.0 m/s"
        sendStopCommand()
    }

    /**
     * 发送控制指令给树莓派
     */
    private fun sendControlCommand(x: Float, y: Float) {
        // 这里实现与树莓派的通信
        println("控制指令 - X: $x, Y: $y")
    }

    /**
     * 发送停止指令
     */
    private fun sendStopCommand() {
        println("停止指令")
    }

    /**
     * 显示提示消息
     */
    private fun showMessage(message: String) {
        android.widget.Toast.makeText(this, message, android.widget.Toast.LENGTH_SHORT).show()
    }

    override fun onDestroy() {
        super.onDestroy()
        // 清理资源
    }
}